<?php
include_once 'modules/Tools.php';
require 'vendor/autoload.php';

import('ORG.Util.Image.ThinkImage');

// 控制台基类
class BaseAction extends Action
{
    public $request;
    public $basePath;
    public $user;

  // 通用初始化方法
    public function _initialize()
    {
        $corsIps = array('127.0.0.1', '172.17.0.1');
        if (in_array($_SERVER['REMOTE_ADDR'], $corsIps)) {
            header("Access-Control-Allow-Origin: http://localhost:8000");
            header("Access-Control-Allow-Credentials:true");
            header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie');
        }

        $this->user = $this->_saveCurrentUserSession();
        $isPublic = $this->_isPublicPage();
        $isAuthorized = true;

        // 将提交参数转换为json
        $this->request = $this->_getRequestData();

        // 合并普通get/post参数
        if (!$this->request) {
            foreach ($_REQUEST as $key => $val) {
                if ($key !== '_URL_') {
                    $this->request[$key] = $val;
                }
            }
        }

        // 登录控制
        if (!$isPublic && empty($this->user)) {
            http_response_code(401);
            // $this->ajaxReturn('', '未登录', 0);
        }

        //权限控制
        if (!$isAuthorized) {
            http_response_code(403);
            // $this->ajaxReturn('', '无权限', 0);
        }

        $this->basePath = $_SERVER['DOCUMENT_ROOT'].'/track/';
    }

  /** 
   * 判断当前页面是否可以公开访问（无需登陆）
   * @return boolean true表示无需登录即可访问
   */
    private function _isPublicPage()
    {
        $publicPages = array('wechat', 'login', 'dologin', 'logout', 'uploadtemplate', 'uploadthumb', 'uploadphoto', 'uploadvideo', 'uploadfile', 'wechatnotify', 'noticetemplate');
        $actionName = strtolower(ACTION_NAME);
        $moduleName = strtolower(MODULE_NAME);
        return $moduleName === 'index' || in_array($actionName, $publicPages) || ($moduleName === 'track' && $actionName === 'create') ;
    }

    public function getUserId() {
      $user = $this->user;
      return $user['id'];
    }

    private function _isAuthorized()
    {
        // 需要验证权限的操作列表
    }

  /**
   * 保存当前用户到session
   * @return object/null 用户数据
   */
    private function _saveCurrentUserSession()
    {
        if (isset($_SESSION['trackUser'])) {
            return $_SESSION['trackUser'];
        } else {
            return null;
        }
    }

  /**
   * 获取json请求
   * @return array 解析后的对象
   */
    private function _getRequestData()
    {
        return json_decode(htmlspecialchars_decode(rawurldecode($this->_param('data'))), true);
        // return json_decode(file_get_contents('php://input'), true);
    }

    public function _getPageLimit($limit = 10)
    {
        $page = $this->request['p'] ? $this->request['p'] : 1;
        $limit = $this->request['limit'] ? $this->request['limit'] : $limit;
        $page = ($page - 1) * $limit;
        return $page.','.$limit;
    }

  /**
   * 通用数据列表展示实现
   * @param  string $modelName 表名/视图模型对象
   * @param  string $orderField 排序字段
   * @param  array $filters 查询时的过滤器数组，数组元素为过滤字段的名称
   * @param  array $conditions 额外查询条件
   * @param  bool  $noLimit 不限制limit，全部查询
   * @return void
   */
    public function _modelList($modelName, $orderField = "createtime desc", $filters = array(), $conditions = array(), $noLimit = false)
    {
        $Model = D($modelName);
        foreach ($conditions as $key => $value) {
            $map[$key] = $value;
        }

        $map['_string'] = $this->_makeSearchSql($filters);

        $count = $Model->where($map)->count();
        $limit = $this->_getPageLimit();

        if ($noLimit) {
            $list = $Model->where($map)->order($orderField)->select();
        } else {
            $list = $Model->where($map)->order($orderField)->limit($limit)->select();
        }
        
        if (!$list) {
            $list = array();
            $count = 0;
        }

        return array("list"=>$list, "count"=>$count);
    }

  /**
   * 组装查询where子句
   * @param  array $filters  需要匹配的字段数组
   * @param  string $searchKey 提交参数中搜索关键字的参数名，默认为search
   * @return string            查询where子句
   */
    public function _makeSearchSql($filters, $searchKey = "search")
    {
        $search = $this->request[$searchKey];
        if ($search && strlen($search) > 0) {
            // 存在搜索字段，遍历需要匹配的字段组合where子句
            $wherePart = array();
            foreach ($filters as $key => $value) {
                $wherePart[] = $value.' LIKE "%'.$search.'%"';
            }
            return implode(" OR ", $wherePart);
        } else {
            // 不存在搜索字段，查询条件返回1，即where 1
            return 1;
        }
    }

  /**
   * 通用数据详情实现
   * @param  stting $modelName 表名
   * @param  string $field     键
   * @param  number $value     值
   * @param  string $fields    查询字段，默认为*
   * @return variable          如果查询到数据，返回数据对象，否则返回false
   */
    public function _modelDetail($modelName, $field, $value, $fields = "*")
    {
        $Model = D($modelName);
        $condition[$field] = $value;
        $ret = $Model->where($condition)->field($fields)->find();

        return $ret;
    }

  /**
   * 通用数据新增实现
   * @param  string $modelName 数据模型名称
   * @param  $postData 表单数据
   * @param  string $name      提示信息中的数据对应名称
   * @return void
   */
    public function _modelAdd($modelName, $name, $postData = null)
    {
        $Model = D($modelName);
        $data = $postData ? $postData : $this->request;

        if ($Model->create($data)) {
            $ret = $Model->add();

            if ($ret) {
                $this->ajaxReturn(trace(), '新增'.$name.'成功', 1);
            } else {
                $this->ajaxReturn(trace(), '新增'.$name.'失败', 0);
            }
        } else {
            $this->ajaxReturn(trace(), $Model->getError(), 0);
        }
    }

    public function _modelDoAdd($modelName, $postData = null)
    {
        $Model = D($modelName);
        $data = $postData ? $postData : $this->request;

        if ($Model->create($data)) {
            $ret = $Model->add();

            if ($ret) {
                return $ret;
            } else {
                return false;
            }
        } else {
            return $Model->getError();
        }
    }

  /**
   * 通用数据删除实现
   * @param  string $modelName 模型名称
   * @return void
   */
    public function _modelDelete($modelName)
    {
        $id = $this->request['id'];
        $Model = M($modelName);
        $ret = $Model->delete($id);

        return $ret;
    }

  /**
   * 通用数据更新实现
   * @param  string $modelName 模型名称
   * @param  string $name      提示信息中的数据对应名称
   * @return void
   */
    public function _modelUpdate($modelName, $name)
    {
        $Model = D($modelName);

        if ($Model->create($this->request)) {
            $ret = $Model->save();
            if ($ret !== false) {
                $this->ajaxReturn('', "更新".$name."成功", 1);
            }

            $this->ajaxReturn(trace(), "更新".$name."失败", 0);
        } else {
            $this->ajaxReturn('', $Model->getError(), 0);
        }
    }

    public function _modelDoUpdate($modelName, $postData = null)
    {
        $Model = D($modelName);
        $data = $postData ? $postData : $this->request;

        if ($Model->create($data)) {
            $ret = $Model->save();
            return $ret;
        } else {
            return $Model->getError();
        }
    }

    /**
     * 上传文件
     * @param array $config 上传配置
     * @return array 上传结果
     */
    public function upload($config = array())
    {
        $savePath = $this->basePath.'Uploads/temp/';
        $_config['maxSize'] = $config['maxSize'] ? $config['maxSize'] : 30;
        if($config['allowExts']) $_config['allowExts'] = $config['allowExts'];


        import('ORG.Net.UploadFile');
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 1024576 * $_config['maxSize'];// 设置附件上传大小
        $upload->allowExts  = $_config['allowExts'];// 设置附件上传类型
        $upload->savePath =  $savePath;// 设置附件上传目录

        if (!$upload->upload()) {// 上传错误提示错误信息
            $msg = $upload->getErrorMsg();
            $extStr = implode(',', $_config['allowExts']);
            $data = '只能上传不超过'.$_config['maxSize'].'MB的'.$extStr.'文件';
            return array("data"=>$data, "info"=>$msg, "status"=>0);
        } else {// 上传成功 获取上传文件信息
            $info = $upload->getUploadFileInfo();
            $data = count($info) > 1 ? $info : $info[0];

            if($config['thumb']) {
              $image = new ThinkImage(THINKIMAGE_GD, $savePath.$data['savename']);
              $image->thumb($config['thumb']['width'], $config['thumb']['height'], 1)->save($savePath.$data['savename'], null, false);
            }

            return array("data"=>$data, "info"=>"上传成功", "status"=>1);
        }
    }

    /**
     * 将上传后的文件从临时目录移动到指定目录
     * @param string $to 要移动到的目录
     * @param string $filename 要移动的文件名
     * @return bool 移动失败返回false
     */
    public function moveUploadFromTemp($to, $filename)
    {
        if (!$to || !$filename) {
            return false;
        }

        $from = $this->basePath.'Uploads/temp/'.$filename;
        $to = $this->basePath.'Uploads/'.$to.'/'.$filename;

        if (file_exists($from)) {
            return rename($from, $to);
        } else {
            return false;
        }
    }
}
